<?php

namespace App\Http\Controllers\Admin;

use App\Http\Requests\FangRequest;
use App\Models\City;
use App\Models\Fang;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
//导入es生成索引类
use Elasticsearch\ClientBuilder;

class FangController extends Controller
{
    //房源列表
    public function index()
    {
        $data = Fang::with(['owner'])->get();
        return view('admin.fang.index',compact('data'));
    }

    //生成房源信息索引
    public function esinit(){
        //得到es客户端对象
        $client = ClientBuilder::create()->setHosts(config('es.host'))->build();
        //创建索引
        $params = [
            //生成索引的名称
            'index' =>  'fang',
            //类型body表
            'body'  =>  [
                'settings'  =>  [
                    //分区数
                    'number_of_shards'  =>  5,
                    //副本数
                    'number_of_replicas' => 1
                ],
                'mappings'  =>  [
                    '_doc'  =>  [
                        '_source'   =>  [
                            'enabled'   =>  true
                        ],
                        //字段 类似表字段,设置类型
                        'properties'    =>   [
                            'fang_name' =>   [
                                'type'  =>'keyword'
                            ],
                            'fang_desn' =>  [
                                'type'  =>  'text',
                                //中文分词
                                'analyzer'  =>  'ik_max_word',
                                'search_analyzer'   =>  'ik_max_word'
                            ]
                        ]
                    ]
                ]
            ]
        ];
        //创建索引
        $response = $client->indices()->create($params);
        dump($response);
    }

    //房源添加 显示
    public function create(Fang $fang)
    {
        $data = $fang->relationData();

        return view('admin.fang.create',$data);
    }

    //地区三级联动
    public function city(Request $request){
        $data = City::where('pid',$request->get('id'))->get(['id','name']);
        return $data;
    }

    //房源添加 处理
    public function store(FangRequest $request)
    {
        //表单数据
        $dopost = $request->except(['token','file']);
        //入库
        $model = Fang::create($dopost);
        //入库成功 发起高德经纬度转换请求
        $client=new Client(['timeout'=>5]);
        //得到请求地址
        $url = config('gaode.geocode');
        $fang_city = City::where('id',$model->fang_city)->value('name');
        $url = sprintf($url,$model->fang_addr,$fang_city);
        //发起请求
        $response = $client->get($url);
        $body = (string)$response->getBody();
        $arr = json_decode($body,true);
        //找到经纬度入库
        if(count($arr['geocodes']) > 0){
            $locationArr = explode(',',$arr['geocodes'][0]['location']);
            $model->update([
                'longitude' => $locationArr[0],
                'latitude' => $locationArr[1]
            ]);
        }
        //添加es索引
        //得到es客户端对象
        $client = ClientBuilder::create()->setHosts(config('es.host'))->build();
        //写文档
        $params = [
            'index' => 'fang',
            'type'  => '_doc',
            'id'=>  $model->id,
            'body'  =>  [
                'fang_name' =>  $model->fang_name,
                'fang_desn' =>  $model->fang_desn,
            ]
        ];
        //添加数据到索引文档中
        $client->index($params);

        //跳转
        return redirect(route('admin.fang.index'))->with('success','添加成功');
    }

    //改变房源状态
    public function changestatus(Request $request){
        //房源id
        $id = $request->get('id');
        //状态
        $status = $request->get('status');
        Fang::where('id',$id)->update(['fang_status'=>$status]);
        return ['status'=>0,'msg'=>'修改状态成功'];
    }

    //
    public function show(Fang $fang)
    {
        //
    }

    //房源修改 显示
    public function edit(Fang $fang)
    {
        //取关联模型数据
        $data = (new Fang())->relationData();
        //得到当前用户市列表
        $currentCityData = City::where('pid',$fang->fang_province)->get();
        //得到当前用户区列表
        $currentRegionData = City::where('pid',$fang->fang_city)->get();
        $data['currentCityData'] = $currentCityData;
        $data['currentRegionData'] = $currentRegionData;
        $data['fang'] = $fang;
        return view('admin.fang.edit',$data);
    }

    //房源修改 处理
    public function update(FangRequest $request, Fang $fang)
    {
        //表单数据
        $putData = $request->except(['_method','_token','file']);
        $fang->update($putData);


        $client= new Client(['timeout'=>5]);
        //得到请求地址
        $url = config('gaode.geocode');
        $fang_city = City::where('id',$fang->fang_city)->value('name');
        $url = sprintf($url,$fang->fang_addr,$fang_city);
        //发起请求
        $response = $client->get($url);
        $body = (string)$response->getBody();
        $arr = json_decode($body,true);
        //找到经纬度入库
        if(count($arr['geocodes']) > 0){
            $locationArr = explode(',',$arr['geocodes'][0]['location']);
            $fang->update([
                'longitude' => $locationArr[0],
                'latitude' => $locationArr[1]
            ]);
        }
        //添加es索引
        //得到es客户端对象
        $client = ClientBuilder::create()->setHosts(config('es.host'))->build();
        //写文档
        $params = [
            'index' => 'fang',
            'type'  => '_doc',
            'id'=>  $fang->id,
            'body'  =>  [
                'fang_name' =>  $fang->fang_name,
                'fang_desn' =>  $fang->fang_desn,
            ]
        ];
        //添加数据到索引文档中
        $client->index($params);

        return redirect(route('admin.fang.index'))->with('success','修改成功');
    }

    //删除房源
    public function destroy(Fang $fang)
    {
        $fang->delete();
        return ['status'=>0,'msg'=>'删除成功'];
    }
}
